<template>
  <el-upload
    class="avatar-uploader"
    :action="action"
    :show-file-list="false"
    :on-success="handleAvatarSuccess"
    :before-upload="beforeAvatarUpload"
  >
    <x-img v-if="value" :src="value" class="avatar" />
    <i v-else class="el-icon-plus avatar-uploader-icon" />
  </el-upload>
</template>

<script>
export default {
  props: {
    action: {
      type: String,
      default: '/common/upload'
    },
    value: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
    }
  },
  methods: {
    handleAvatarSuccess(res, file) {
      this.$emit('input', res.data.filePath)
    },
    beforeAvatarUpload(file) {
      const isJPG = ['image/jpg', 'image/jpeg', 'image/png'].includes(file.type)
      if (!isJPG) {
        this.$message({
          message: '上传头像图片是 PNG JPEG JPG 格式!',
          type: 'error'
        })
      }
      return isJPG
    }
  }
}
</script>

<style lang="scss" scoped>
  ::v-deep.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  ::v-deep.avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  ::v-deep.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  ::v-deep.avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
